package com.entrogy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.*;
import com.entrogy.dao.StudentAttendanceMapper;
import com.entrogy.dao.TemperatureAnalysisMapper;
import com.entrogy.service.ClassService;
import com.entrogy.service.StudentAttendanceService;
import com.entrogy.service.TemperatureAnalysisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @ClassName TemperatureAnalysisServiceImpl
 * @Description
 * @Author luoxingjiang
 * @Date 2020-02-28 上午 10:49
 * @Version 1.0
 **/
@Service
public class TemperatureAnalysisServiceImpl implements TemperatureAnalysisService {

    private static final Logger logger = LoggerFactory.getLogger(TemperatureAnalysisServiceImpl.class);

    @Autowired
    private TemperatureAnalysisMapper temperatureAnalysisMapper;

    @Autowired
    private StudentAttendanceService studentAttendanceService;

    @Autowired
    private ClassService classService;

    @Autowired
    private StudentAttendanceMapper studentAttendanceMapper;

    @Override
    public TemperatureAnalysisEntity getSchoolTeacherTemperatureInfoOverview(Integer schoolCode, Date selectDate, Double normalTemperate) {
        return temperatureAnalysisMapper.getSchoolTeacherTemperatureInfoOverview(schoolCode, selectDate, normalTemperate);
    }

    @Override
    public TemperatureAnalysisEntity getSchoolStudentTemperatureInfoOverview(Integer schoolCode, Date selectDate,
                                                                             Double normalTemperate, Integer timeFrameType) {
        TemperatureAnalysisEntity temperatureAnalysis = new TemperatureAnalysisEntity();
        // 全校测温的数据，这些数据由每个年级汇总
        Integer totalCount = 0;
        Integer noCheckTemperature = 0;
        Integer checkTemperature = 0;
        Integer temperatureNormalCount = 0;
        Integer temperatureAbnormalCount = 0;
        List<TemperatureAnalysisEntity> gradeTemperatureInfoList = listGradeTemperatureInfoOverview(schoolCode, timeFrameType, selectDate, normalTemperate);
        for (TemperatureAnalysisEntity gradeTemperatureInfo : gradeTemperatureInfoList) {
            totalCount += gradeTemperatureInfo.getTotalCount();
            // 如果该年级的未测人数为null，说明没有到该年级该时段的考勤时间或者没有设置该时间段的考勤时间，则该年级的未测温人数为该年级的总数
            if (gradeTemperatureInfo.getNoCheckTemperature() == null) {
                noCheckTemperature += gradeTemperatureInfo.getTotalCount();
            } else {
                noCheckTemperature += gradeTemperatureInfo.getNoCheckTemperature();
            }
            if (gradeTemperatureInfo.getCheckTemperature() != null) {
                checkTemperature += gradeTemperatureInfo.getCheckTemperature();
            }
            if (gradeTemperatureInfo.getTemperatureNormalCount() != null) {
                temperatureNormalCount += gradeTemperatureInfo.getTemperatureNormalCount();
            }
            if (gradeTemperatureInfo.getTemperatureAbnormalCount() != null) {
                temperatureAbnormalCount += gradeTemperatureInfo.getTemperatureAbnormalCount();
            }
        }
        temperatureAnalysis.setNoCheckTemperature(noCheckTemperature)
                .setCheckTemperature(checkTemperature).setTotalCount(totalCount)
                .setTemperatureAbnormalCount(temperatureAbnormalCount)
                .setTemperatureNormalCount(temperatureNormalCount);
        return temperatureAnalysis;
    }

    @Override
    public List<TemperatureAnalysisEntity> listGradeTemperatureInfoOverview(Integer schoolCode, Integer timeFrameType, Date selectDate, Double normalTemperate) {
        // 查询学校所有的年级
        Map<String, Object> params = new HashMap();
        params.put("schoolCode", schoolCode);
        params.put("type", 2);
        params.put("parentId", 1);
        List<ClassEntity> gradeList = classService.getClassList(params);
        // 存储每个年级的体温统计数据
        List<TemperatureAnalysisEntity> gradeTemperatureInfoList = new ArrayList<>();
        String date = new SimpleDateFormat("yyyy-MM-dd").format(selectDate);
        String dynArrangeTableName = "dyn_arrange" + new SimpleDateFormat("yyyyMMdd").format(selectDate);
        for (ClassEntity grade : gradeList) {
            String startTime = date;
            String endTime = date;
            if (timeFrameType == 1) {
                GradeAttendanceTimeEntity gradeAttendance = studentAttendanceMapper.getGradeMorningAttendanceTime(schoolCode, grade.getId());
                if (gradeAttendance == null || !studentAttendanceService.isArriveGradeAttendanceTime(timeFrameType, grade.getId(), schoolCode, null, selectDate)) {
                    startTime += " 00:00:00";
                    endTime += " 00:00:00";
                    TemperatureAnalysisEntity gradeTemperatureInfo = temperatureAnalysisMapper.getGradeStudentTemperatureInfoOverview(startTime, endTime, schoolCode, grade.getId(), normalTemperate);
                    gradeTemperatureInfo.setId(grade.getId());
                    gradeTemperatureInfo.setName(grade.getClassName());
                    // 没有到统计时间段或者没有设置该考勤时间段的该年级的时间的话，就用null表示
                    gradeTemperatureInfo.setTemperatureNormalCount(null)
                            .setTemperatureAbnormalCount(null)
                            .setCheckTemperature(null)
                            .setNoCheckTemperature(null);
                    gradeTemperatureInfoList.add(gradeTemperatureInfo);
                    continue;
                } else {
                    // 拼接要统计的中午的考勤时间段
                    startTime += " " + gradeAttendance.getStartTime() + ":00";
                    endTime += " " + gradeAttendance.getEndTime() + ":00";
                }
            } else if (timeFrameType == 2 || timeFrameType == 3) {
                // 如果查询的是中午或下午的体温记录，那就查询该班级中午的考勤时间段，如果是下午的话就查询下午
                String startTimeAndEndTime = studentAttendanceService.getGradeAttendanceTimeFrame(timeFrameType, grade.getId(), schoolCode, dynArrangeTableName);
                // 如果startTimeAndEndTime为空则该班级所在年级没有设置中午或者下午的考勤时间
                if (startTimeAndEndTime == null || !studentAttendanceService.isArriveGradeAttendanceTime(timeFrameType, grade.getId(), schoolCode, dynArrangeTableName, selectDate)) {
                    startTime += " 00:00:00";
                    endTime += " 00:00:00";
                    TemperatureAnalysisEntity gradeTemperatureInfo = temperatureAnalysisMapper.getGradeStudentTemperatureInfoOverview(startTime, endTime, schoolCode, grade.getId(), normalTemperate);
                    gradeTemperatureInfo.setId(grade.getId());
                    gradeTemperatureInfo.setName(grade.getClassName());
                    // 没有到统计时间段或者没有设置该考勤时间段的该年级的时间的话，就用null表示
                    gradeTemperatureInfo.setTemperatureNormalCount(null)
                            .setTemperatureAbnormalCount(null)
                            .setCheckTemperature(null)
                            .setNoCheckTemperature(null);
                    gradeTemperatureInfoList.add(gradeTemperatureInfo);
                    continue;
                } else {
                    String[] temp = startTimeAndEndTime.split("-");
                    // 拼接要统计的中午的考勤时间段
                    startTime += " " + temp[0] + ":00";
                    endTime += " " + temp[1] + ":00";
                }
            }
            TemperatureAnalysisEntity gradeTemperatureInfo = temperatureAnalysisMapper.getGradeStudentTemperatureInfoOverview(startTime, endTime, schoolCode, grade.getId(), normalTemperate);
            gradeTemperatureInfo.setId(grade.getId());
            gradeTemperatureInfo.setName(grade.getClassName());
            gradeTemperatureInfo.setCheckTemperature(gradeTemperatureInfo.getTotalCount() - gradeTemperatureInfo.getNoCheckTemperature());
            gradeTemperatureInfoList.add(gradeTemperatureInfo);
        }
        return gradeTemperatureInfoList;
    }

    @Override
    public List<TemperatureAnalysisEntity> listClassTemperatureInfoOverview(Date selectDate, Integer schoolCode, Integer gradeId, Integer timeFrameType, Double normalTemperate) {
        // 查询学校所有的班级
        Map<String, Object> params = new HashMap();
        params.put("schoolCode", schoolCode);
        params.put("type", 2);
        params.put("parentId", gradeId);
        List<ClassEntity> classList = classService.getClassList(params);
        // 存储每个班级的体温统计数据
        List<TemperatureAnalysisEntity> classTemperatureInfoList = new ArrayList<>();
        String date = new SimpleDateFormat("yyyy-MM-dd").format(selectDate);
        String dynArrangeTableName = "dyn_arrange" + new SimpleDateFormat("yyyyMMdd").format(selectDate);
        GradeAttendanceTimeEntity gradeAttendance = studentAttendanceMapper.getGradeMorningAttendanceTime(schoolCode, gradeId);
        // 如果查询的是中午或下午的体温记录，那就查询该班级中午的考勤时间段，如果是下午的话就查询下午
        for (ClassEntity classEntity : classList) {
            String startTime = date;
            String endTime = date;
            if (timeFrameType == 1) {
                if (gradeAttendance == null || !studentAttendanceService.isArriveGradeAttendanceTime(timeFrameType, gradeId, schoolCode, null, selectDate)) {
                    startTime += " 00:00:00";
                    endTime += " 00:00:00";
                    TemperatureAnalysisEntity classTemperatureInfo = temperatureAnalysisMapper.getClassStudentTemperatureInfoOverview(startTime, endTime, schoolCode, classEntity.getId(), normalTemperate);
                    classTemperatureInfo.setId(classEntity.getId());
                    classTemperatureInfo.setName(classEntity.getClassName());
                    // 没有到统计时间段或者没有设置该考勤时间段的该年级的时间的话，就用null表示
                    classTemperatureInfo.setTemperatureNormalCount(null)
                            .setTemperatureAbnormalCount(null).setCheckTemperature(null)
                            .setNoCheckTemperature(null);
                    classTemperatureInfoList.add(classTemperatureInfo);
                    continue;
                } else {
                    // 拼接要统计的中午的考勤时间段
                    startTime += " " + gradeAttendance.getStartTime() + ":00";
                    endTime += " " + gradeAttendance.getEndTime() + ":00";
                }
            } else if (timeFrameType == 2 || timeFrameType == 3) {
                String startTimeAndEndTime = studentAttendanceService.getClassAttendanceTimeFrame(timeFrameType, classEntity.getId(), schoolCode, dynArrangeTableName);
                // 如果startTimeAndEndTime为空则该班级所在年级没有设置中午或者下午的考勤时间
                if (startTimeAndEndTime == null || !studentAttendanceService.isArriveGradeAttendanceTime(timeFrameType, gradeId, schoolCode, dynArrangeTableName, selectDate)) {
                    startTime += " 00:00:00";
                    endTime += " 00:00:00";
                    TemperatureAnalysisEntity classTemperatureInfo = temperatureAnalysisMapper.getClassStudentTemperatureInfoOverview(startTime, endTime, schoolCode, classEntity.getId(), normalTemperate);
                    classTemperatureInfo.setId(classEntity.getId());
                    classTemperatureInfo.setName(classEntity.getClassName());
                    // 没有到统计时间段或者没有设置该考勤时间段的该年级的时间的话，就用null表示
                    classTemperatureInfo.setTemperatureNormalCount(null)
                            .setTemperatureAbnormalCount(null).setCheckTemperature(null)
                            .setNoCheckTemperature(null);
                    classTemperatureInfoList.add(classTemperatureInfo);
                    continue;
                } else {
                    String[] temp = startTimeAndEndTime.split("-");
                    // 拼接要统计的中午的考勤时间段
                    startTime += " " + temp[0] + ":00";
                    endTime += " " + temp[1] + ":00";
                }
            }
            TemperatureAnalysisEntity classTemperatureInfo = temperatureAnalysisMapper.getClassStudentTemperatureInfoOverview(startTime, endTime, schoolCode, classEntity.getId(), normalTemperate);
            classTemperatureInfo.setId(classEntity.getId());
            classTemperatureInfo.setName(classEntity.getClassName()).setCheckTemperature(classTemperatureInfo.getTemperatureAbnormalCount() + classTemperatureInfo.getTemperatureNormalCount());
            classTemperatureInfoList.add(classTemperatureInfo);
        }
        return classTemperatureInfoList;
    }

    @Override
    public List<TeacherTemperatureInfoEntity> listTeacherTemp(Integer schoolCode, Double normalTemperature, boolean normalFlag, LocalDateTime startTime, LocalDateTime endTime) {
        return temperatureAnalysisMapper.listTeacherTemp(schoolCode, normalTemperature, normalFlag, startTime, endTime);
    }


    @Override
    public List<StudentTemperatureInfoEntity> listStudentTemp(Integer schoolCode, Double normalTemperature,
                                                              boolean normalFlag, LocalDateTime startTime,
                                                              LocalDateTime endTime, Integer gradeId, Integer classId) {
        return temperatureAnalysisMapper.listStudentTemp(schoolCode, normalTemperature, normalFlag, startTime, endTime, gradeId, classId);
    }

    @Override
    public List<StudentTemperatureInfoEntity> listChildTempInfo(String parentId, LocalDateTime startTime, LocalDateTime endTime, Integer studentId) {
        return temperatureAnalysisMapper.listChildTempInfo(parentId, startTime, endTime, studentId);
    }

    @Override
    public List<StudentTemperatureInfoEntity> listStudentTemp(Integer schoolCode,
                                                              Double normalTemperature, boolean normalFlag,
                                                              Integer gradeId, Integer classId, Integer timeFrameType, String selectDate) {
        // 查询开始和截止时间
        Map<String, LocalDateTime> selectTime = getSelectTime(schoolCode, gradeId, classId, timeFrameType, selectDate);
        if (selectTime == null) {
            return null;
        }
        List<StudentTemperatureInfoEntity> studentTemperatureInfoList = temperatureAnalysisMapper.listStudentTemp(schoolCode, normalTemperature,
                normalFlag, selectTime.get("startTime"), selectTime.get("endTime"), gradeId, classId);
        return studentTemperatureInfoList;
    }

    public Map<String, LocalDateTime> getSelectTime(Integer schoolCode,
                                                    Integer gradeId, Integer classId, Integer timeFrameType, String selectDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Date parseDate = null;
        try {
            parseDate = format.parse(selectDate);
        } catch (ParseException e) {
            e.printStackTrace();
            logger.error("时间格式有误！");
            return null;
        }
        String zero = " 00:00:00";
        String dynArrangeTableName = "dyn_arrange" + new SimpleDateFormat("yyyyMMdd").format(parseDate);
        // 定义查询的开始时间和结束时间
        String startTime = selectDate.substring(0, 10);
        String endTime = selectDate.substring(0, 10);

        if (classId != null) {   // 查询该班级该时段的考勤时间用于统计人员详情
            JSONObject classAttendance = studentAttendanceMapper.getClassMorningAttendanceTime(classId, schoolCode);
            if (timeFrameType == 1) {
                if (classAttendance == null || !studentAttendanceService.isArriveAttendanceTime(timeFrameType, classId, schoolCode, null, parseDate)) {
                    startTime += zero;
                    endTime += zero;
                } else {
                    // 拼接要统计的中午的考勤时间段
                    startTime += " " + classAttendance.getString("startTime");
                    endTime += " " + classAttendance.getString("endTime");
                }
            } else if (timeFrameType == 2 || timeFrameType == 3) {
                String startTimeAndEndTime = studentAttendanceService.getClassAttendanceTimeFrame(timeFrameType, classId, schoolCode, dynArrangeTableName);
                // 如果startTimeAndEndTime为空则该班级所在年级没有设置中午或者下午的考勤时间
                if (startTimeAndEndTime == null || !studentAttendanceService.isArriveAttendanceTime(timeFrameType, classId, schoolCode, dynArrangeTableName, parseDate)) {
                    startTime += zero;
                    endTime += zero;
                } else {
                    String[] temp = startTimeAndEndTime.split("-");
                    // 拼接要统计的中午的考勤时间段
                    startTime += " " + temp[0] + ":00";
                    endTime += " " + temp[1] + ":00";
                }
            }
        } else if (gradeId != null) {   // 查询该年级该时段的考勤时间用于统计人员详情
            GradeAttendanceTimeEntity gradeAttendance = studentAttendanceMapper.getGradeMorningAttendanceTime(schoolCode, gradeId);
            if (timeFrameType == 1) {
                if (gradeAttendance == null || !studentAttendanceService.isArriveGradeAttendanceTime(timeFrameType, gradeId, schoolCode, null, parseDate)) {
                    startTime += zero;
                    endTime += zero;
                } else {
                    // 拼接要统计的中午的考勤时间段
                    startTime += " " + gradeAttendance.getStartTime();
                    endTime += " " + gradeAttendance.getEndTime();
                }
            } else if (timeFrameType == 2 || timeFrameType == 3) {
                String startTimeAndEndTime = studentAttendanceService.getGradeAttendanceTimeFrame(timeFrameType, gradeId, schoolCode, dynArrangeTableName);
                // 如果startTimeAndEndTime为空则该班级所在年级没有设置中午或者下午的考勤时间
                if (startTimeAndEndTime == null || !studentAttendanceService.isArriveGradeAttendanceTime(timeFrameType, gradeId, schoolCode, dynArrangeTableName, parseDate)) {
                    startTime += zero;
                    endTime += zero;
                } else {
                    String[] temp = startTimeAndEndTime.split("-");
                    // 拼接要统计的中午的考勤时间段
                    startTime += " " + temp[0] + ":00";
                    endTime += " " + temp[1] + ":00";
                }
            }
        } else if (schoolCode != null) { // 查询该学校该时段的最早考勤时间和最晚考勤时间用于统计人员详情
            String earliestAttendanceTime;
            String latestAttendanceTime;
            if (timeFrameType == 2 || timeFrameType == 3) {
                // 找到学校中午、下午时间段的最早、最晚的考勤时间
                List<JSONObject> attendanceTimeList = classService.listAttendanceTime(schoolCode, dynArrangeTableName);
                if (attendanceTimeList.size() > 0) {
                    // 如果timeFrameType等于2就找学校中午时段最早的考勤时间段，如果等于3就找学校下午时段最早的考勤时间段
                    earliestAttendanceTime = timeFrameType == 2 ? attendanceTimeList.get(0).getString("afternoon").split("-")[0]
                            : attendanceTimeList.get(0).getString("evening").split("-")[0];
                    latestAttendanceTime = timeFrameType == 2 ? attendanceTimeList.get(0).getString("afternoon").split("-")[1]
                            : attendanceTimeList.get(0).getString("evening").split("-")[1];
                    for (int i = 1; i < attendanceTimeList.size(); i++) {
                        String time = timeFrameType == 2 ? attendanceTimeList.get(i).getString("afternoon").split("-")[0]
                                : attendanceTimeList.get(i).getString("evening").split("-")[0];
                        if (earliestAttendanceTime.compareTo(time) > 0) {
                            earliestAttendanceTime = time;
                        }
                        time = timeFrameType == 2 ? attendanceTimeList.get(i).getString("afternoon").split("-")[1]
                                : attendanceTimeList.get(i).getString("evening").split("-")[1];
                        if (latestAttendanceTime.compareTo(time) < 0) {
                            latestAttendanceTime = time;
                        }
                    }
                    startTime += " " + earliestAttendanceTime + ":00";
                    endTime += " " + latestAttendanceTime + ":00";
                } else {
                    return null;
                }
            }
            if (timeFrameType == 1) {
                List<GradeAttendanceTimeEntity> gradeAttendanceList = studentAttendanceMapper.listGradeMorningAttendanceTime(schoolCode);
                earliestAttendanceTime = gradeAttendanceList.get(0).getStartTime();
                latestAttendanceTime = gradeAttendanceList.get(0).getEndTime();
                for (int i = 0; i < gradeAttendanceList.size(); i++) {
                    String time = gradeAttendanceList.get(i).getStartTime();
                    if (earliestAttendanceTime.compareTo(time) > 0) {
                        earliestAttendanceTime = time;
                    }
                    time = gradeAttendanceList.get(i).getEndTime();
                    if (latestAttendanceTime.compareTo(time) < 0) {
                        latestAttendanceTime = time;
                    }
                }
                startTime += " " + earliestAttendanceTime;
                endTime += " " + latestAttendanceTime;
            }

        }
        Map<String, LocalDateTime> selectTime = new HashMap<>();
        selectTime.put("startTime", LocalDateTime.parse(startTime, df));
        selectTime.put("endTime", LocalDateTime.parse(endTime, df));
        return selectTime;
    }


}
